import crypto from 'crypto'

// MD5加密
export const sign = (str) => {
  const md5 = crypto.createHash('md5')
  md5.update(str)
  return md5.digest('hex')
}
export const vibrate = (timeout) => {
  if (navigator.vibrate) {
    navigator.vibrate(timeout)
  } else if (navigator.webkitVibrate) {
    navigator.webkitVibrate(timeout)
  }
}

/**
 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
export const getTextWidth = (text, font) => {
  // re-use canvas object for better performance
  var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement('canvas'))
  var context = canvas.getContext('2d')
  context.font = font
  var metrics = context.measureText(text)
  return metrics.width
}

export const getTextWidth2 = (str) => {
  const dom = document.createElement('span')
  dom.style.display = 'inline-block'
  dom.textContent = str
  document.body.appendChild(dom)
  const width = dom.clientWidth
  console.log(dom.clientWidth)
  document.body.removeChild(dom)
  return width
}

//判断对象是否为空
export const  isNotNull=(obj)=>{
  let _value=false;
  if(obj==undefined||obj==null||obj=='')
  _value=false
  else
  _value=true;
  return _value;
}

//判断当前浏览器版本
export const isBrowser=()=>{
  var userAgent = navigator.userAgent;
  //微信内置浏览器
  if(userAgent.match(/MicroMessenger/i) == 'MicroMessenger') {
      return "MicroMessenger";
  }
  //QQ内置浏览器
  else if(userAgent.match(/QQ/i) == 'QQ') {
      return "QQ";
  }
  //Chrome
  else if(userAgent.match(/Chrome/i) == 'Chrome') {
      return "Chrome";
  }
  //Opera
  else if(userAgent.match(/Opera/i) == 'Opera') {
      return "Opera";
  }
  //Firefox
  else if(userAgent.match(/Firefox/i) == 'Firefox') {
      return "Firefox";
  }
  //Safari
  else if(userAgent.match(/Safari/i) == 'Safari') {
      return "Safari";
  }
  //IE
  else if(!!window.ActiveXObject || "ActiveXObject" in window) {
      return "IE";
  }
  else {
      return "未定义:"+userAgent;
  }
}